package com.hospital.diagnosis.module.controller;

import cn.hutool.core.date.DateUtil;
import com.hospital.common.base.PageResult;
import com.hospital.common.base.Result;
import com.hospital.common.base.ThreadAttributes;
import com.hospital.common.dto.diagnosis.module.ChatStatusDTO;
import com.hospital.common.pojo.TChatLog;
import com.hospital.common.pojo.TChatSession;
import com.hospital.common.pojo.TDepartment;
import com.hospital.common.utils.ThreadLocalUtils;
import com.hospital.diagnosis.module.dto.CreateChatDTO;
import com.hospital.diagnosis.module.exception.ServiceException;
import com.hospital.diagnosis.module.service.ChatService;
import com.hospital.diagnosis.module.utils.MinioUtils;
import com.hospital.diagnosis.module.vo.ChatSessionVo;
import com.hospital.diagnosis.module.vo.DoctorVo;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.List;
import java.util.UUID;

import static com.hospital.diagnosis.module.exception.enums.ExceptionCode.FORBIDDEN;

@RestController
@RequestMapping("/chat")
public class ChatController
{
    @Autowired
    private ChatService chatService;
    @Autowired
    private MinioUtils minioUtils;

    // 最大文件大小（10MB）
    private static final Long MAX_FILE_SIZE = 10 * 1024 * 1024L;

    // 允许的文件类型
    private static final List<String> ALLOWED_EXTENSIONS = Arrays.asList(
            ".jpg", ".jpeg", ".png", ".gif", ".pdf", ".doc", ".docx"
    );

    /**
     * 获取所有科室
     * @return 科室对象列表
     */
    @GetMapping("/getDepartments")
    public Result getDepartments(){
        List<TDepartment> departments= chatService.getDepartments();
        return Result.success(departments);
    }

    /**
     * 获取指定科室所有在班医生
     * @param departmentId 科室ID |1
     * @return 医生对象列表
     */
    @GetMapping("/getDoctors")
    public Result getDoctors(@RequestParam(value = "departmentId") @NotNull(message = "科室id不能为空") Long departmentId){
        List<DoctorVo> doctors= chatService.getDoctors(departmentId);
        return Result.success(doctors);
    }

    /**
     * 获取指定科室所有医生
     * @param departmentId 科室ID |1
     * @return 医生对象列表
     */
    @GetMapping("/getAllDoctors")
    public Result getAllDoctors(@RequestParam(value = "departmentId") @NotNull(message = "科室id不能为空") Long departmentId){
        List<DoctorVo> doctors= chatService.getAllDoctors(departmentId);
        return Result.success(doctors);
    }

    /**
     * 更新会话状态
     * @param chatStatusDTO
     * @return 更新结果
     */
    @PutMapping("/updateChatStatus")
    public Result updateChatStatus(@RequestBody @Validated ChatStatusDTO chatStatusDTO){
        if(!chatService.updateChatStatus(chatStatusDTO.getSessionId(),chatStatusDTO.getStatus())){
            return Result.fail("更新会话状态失败");
        }

        return Result.success();
    }

    /**
     * 创建会话
     * @param chatStatusDTO
     * @return 创建结果
     */
    @PostMapping("/createChat")
    public Result createChat(@RequestBody @Validated CreateChatDTO chatStatusDTO){
        ThreadAttributes ta = ThreadLocalUtils.get();
        if(ta==null||ta.getRoleType()!=0){
            throw new ServiceException(FORBIDDEN);
        }

        if(!chatService.createChat(chatStatusDTO.getDoctorId(),ta.getUserId())){
            return Result.fail("创建会话失败");
        }
        return Result.success("创建会话成功");
    }

    /**
     * 获取会话列表
     * @return 会话列表
     */
    @GetMapping("/getChats")
    public Result getChats(){
        ThreadAttributes ta = ThreadLocalUtils.get();
        if(ta==null){
            throw new ServiceException(FORBIDDEN);
        }

        List<TChatSession> chats= chatService.getChats(ta.getUserId());

        return Result.success(chats);
    }

    /**
     * 获取医生未读消息数量
     * @return 未读消息数量
     */
    @GetMapping("/getUnreadCount")
    public Result getUnreadCount(){

        ThreadAttributes ta =ThreadLocalUtils.get();
        Long doctorId=ta.getRoleType()==1?ta.getUserId():0L;

        Integer count=chatService.getUnreadCount(doctorId);

        return Result.success("OK",count);
    }

    /**
     * 获取已归档会话列表
     * @return 会话列表
     */
    @GetMapping("/getAllArchivedChats")
    public Result getAllArchivedChats(@RequestParam(value = "doctorId") @NotNull(message = "医生id不能为空") Long doctorId,
                                   @RequestParam(value = "patientName",required = false) String patientName,
                                   @RequestParam(value = "startTime",required = false) String startTime,
                                   @RequestParam(value = "endTime",required = false) String endTime,
                                   @RequestParam(value = "pageNum") @NotNull(message = "页码不能为空") Integer pageNum,
                                   @RequestParam(value = "pageSize") @NotNull(message = "页大小不能为空") Integer pageSize){
        Integer count=chatService.getAllArchivedChatsCount(doctorId,patientName,startTime,endTime);
        if(count==0){
            return Result.success("无在线问诊聊天记录");
        }
        List<ChatSessionVo> chatSessionVos = chatService.getAllArchivedChats(doctorId,patientName,startTime,endTime,pageNum,pageSize);
        return Result.success(new PageResult((long)count,chatSessionVos));
    }

    @GetMapping("/getArchivedChatLogs")
    public Result getArchivedChatLogs(@RequestParam(value = "sessionId") @NotBlank(message = "会话id不能为空") String sessionId){
        List<TChatLog> chatLogs = chatService.getChatLogsBySessionId(sessionId);
        return Result.success(chatLogs);
    }

    /**
     * 上传文件
     * @param file 文件
     * @return 文件名称（含路径）
     */
    @PostMapping("/upload")
    public Result upload(@RequestParam("file") @NotNull(message = "文件不能为空") MultipartFile file) throws Exception {
        if(file.getSize()>MAX_FILE_SIZE){
            throw new IllegalAccessException("文件过大");
        }
        String ext = file.getOriginalFilename().substring( file.getOriginalFilename().lastIndexOf("."));
        if (!ALLOWED_EXTENSIONS.contains(ext)) {
            throw new IllegalArgumentException("不支持的文件类型，仅支持: " + ALLOWED_EXTENSIONS);
        }

        //随机文件名
        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); //扩展名
        String fileName = DateUtil.today().replace("-", "")+"/"+ UUID.randomUUID().toString() + fileExtension; //日期目录下UUID+扩展名
        return Result.success("上传成功",minioUtils.uploadFile(file,fileName));
    }

    /**
     * 获取minio文件地址
     * @param fileName 文件名（含路径）
     * @return 文件访问地址
     */
    @GetMapping("/getUrl")
    public Result getFileUrl(@RequestParam("fileName") @NotNull(message = "文件名不能为空") String fileName){
        String url =minioUtils.getPresignedUrl(fileName);
        if(url==null){
            return Result.fail("获取文件地址失败");
        }
        return Result.success("获取文件地址成功",url);
    }

}
